using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services
{
    public class LoginSessionService : BaseService<LoginSession>, ILoginSessionService
    {
        public LoginSessionService(PandaSystemContext context) : base(context)
        {
        }

        public async Task<LoginSession?> GetByTokenAsync(string token)
        {
            return await _dbSet
                .Include(s => s.User)
                .FirstOrDefaultAsync(s => s.SessionToken == token && s.IsActive == true);
        }

        public async Task<List<LoginSession>> GetActiveSessionsByUserIdAsync(Guid userId)
        {
            return await _dbSet
                .Where(s => s.UserId == userId && s.IsActive == true && s.ExpiresAt > DateTime.UtcNow)
                .OrderByDescending(s => s.CreatedAt)
                .ToListAsync();
        }

        public async Task<bool> DeactivateSessionAsync(Guid sessionId)
        {
            var session = await _dbSet.FindAsync(sessionId);
            if (session == null)
                return false;

            session.IsActive = false;
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeactivateAllUserSessionsAsync(Guid userId)
        {
            var sessions = await _dbSet
                .Where(s => s.UserId == userId && s.IsActive == true)
                .ToListAsync();

            foreach (var session in sessions)
            {
                session.IsActive = false;
            }

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> IsSessionValidAsync(string token)
        {
            var session = await _dbSet
                .FirstOrDefaultAsync(s => s.SessionToken == token);

            return session != null && 
                   session.IsActive == true && 
                   session.ExpiresAt > DateTime.UtcNow;
        }

        public override async Task<LoginSession> CreateAsync(LoginSession session)
        {
            // 设置默认值
            session.SessionId = Guid.NewGuid();
            session.CreatedAt = DateTime.UtcNow;
            session.IsActive = true;
            
            // 如果没有设置过期时间，默认设置为24小时后
            if (session.ExpiresAt == default)
            {
                session.ExpiresAt = DateTime.UtcNow.AddHours(24);
            }

            await _dbSet.AddAsync(session);
            await _context.SaveChangesAsync();
            
            return session;
        }

        public override async Task<bool> DeleteAsync(Guid id)
        {
            var session = await _dbSet.FindAsync(id);
            if (session == null)
                return false;

            _dbSet.Remove(session);
            await _context.SaveChangesAsync();
            
            return true;
        }

        public override async Task<LoginSession> UpdateAsync(LoginSession session)
        {
            var existingSession = await _dbSet.FindAsync(session.SessionId);
            if (existingSession == null)
                throw new KeyNotFoundException($"Session with ID {session.SessionId} not found.");

            // 只允许更新特定字段
            existingSession.DeviceInfo = session.DeviceInfo;
            existingSession.Ipaddress = session.Ipaddress;
            existingSession.ExpiresAt = session.ExpiresAt;
            existingSession.IsActive = session.IsActive;

            await _context.SaveChangesAsync();
            return existingSession;
        }
    }
} 